package com.scpii.universal.struts.produce;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.scpii.universal.action.BaseAction;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.hibernate.entity.AppIconTab;
import com.scpii.universal.hibernate.entity.AppUpdateTab;
import com.scpii.universal.hibernate.entity.FlagEntity;
import com.scpii.universal.hibernate.entity.ManageUserTab;
import com.scpii.universal.service.AppIconService;
import com.scpii.universal.service.AppUpdateService;
import com.scpii.universal.service.AttributeListService;
import com.scpii.universal.service.ManageUserService;
import com.scpii.universal.util.EhCacheManager;

@Controller
@Scope("prototype")
public class AdminProcessAction extends BaseAction {

	private static final long serialVersionUID = 7696906808590977502L;
	private Log log = LogFactory.getLog(this.getClass());
	@Resource
	private AppIconService appIconService;
	@Resource
	private ManageUserService manageUserService;
	@Resource
	private AttributeListService attributeListService;
	@Resource
	private AppUpdateService appUpdateService;

	public String changeFlag() {
		String flagKey = request.getParameter("flagKey");
		String flagValue = request.getParameter("flagValue");
		EhCacheManager.addObject(flagKey, flagValue);
		log.info("改变配置" + flagKey + "为" + flagValue);
		return null;
	}
	
	public String getFlag() throws IOException {
		List<?> lst = (List<?>) EhCacheManager.getAllObjects();
		List<FlagEntity> results = new ArrayList<FlagEntity>();
		for (Object object : lst) {
			if (GenericConstants.REGISTER_PAGE_SHOW.equals(object.toString()))
				continue;
			FlagEntity ent = new FlagEntity();
			ent.setKey(object.toString());
			ent.setValue(EhCacheManager.getObject(object.toString()));
			results.add(ent);
		}
		jsonOut(JSONArray.fromObject(results).toString());
		return null;
	}
	
	public String doSysMatrialUpload() throws Exception {
		String base = request.getParameter("filePath");
		int type = Integer.parseInt(request.getParameter("type"));
		List items = getBatchResFromRequest(base);
		FileItem item = null;
		String fileName = null;
		AppIconTab icon = null;
		String baseUrl = getIconUrl(type);
		for (int i = 0 ;i < items.size(); i++){
			item = (FileItem) items.get(i);
			fileName = base + File.separator + item.getName();
			// 保存文件
			if (!item.isFormField() && item.getName().length() > 0) {
				item.write(new File(fileName));
				//入库
				icon = new AppIconTab();
				icon.setIntAppId(0);
				icon.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				icon.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
				icon.setIntIconDefineType(GenericConstants.ICON_DEFINE_TYPE_SYS);
				icon.setIntIconName(item.getName());
				icon.setIntIconType((byte)type);
				icon.setVarIconUrl(baseUrl+"/"+item.getName());
				appIconService.save(icon);
			}
		}
		return null;
	}
	
	public String queryUserInfo() throws IOException {
		String keyWord = request.getParameter("keyWord");
		keyWord = URLDecoder.decode(URLDecoder.decode(keyWord,"utf-8"),"utf-8");
		List<ManageUserTab> users = manageUserService.getUsersByLoginName(keyWord);
		StringBuffer datas = new StringBuffer();
		ManageUserTab manageUserTab = null;
		for (int i = 0; i < users.size(); i++) {
			manageUserTab = users.get(i);
			if(manageUserTab.getVarRoleType()==0){
				datas.append("生成平台账号:"+manageUserTab.getVarLoginName()+",");
			} else if(manageUserTab.getVarRoleType()==1){
				datas.append("内容平台账号:"+manageUserTab.getVarLoginName()+",");
			}
			if (i % 2 == 1) {
				int appId = manageUserTab.getIntAppId()==null?0: manageUserTab.getIntAppId();
				datas.append("应用ID:<a href='javascript:void(0)' onclick='queryAppInfo("+appId+")'>" + appId+"</a>");
				datas.append("<br>");
			}
		}
		if(users.size() > 0 ){
			jsonOut(datas.toString());
		}
		return null;
	}
	
	public String queryAppInfo() {
		return null;
	}
	
	public String insertAttrOptions() throws IOException {
		int type = Integer.parseInt(request.getParameter("type"));
		String options = request.getParameter("options");
		options = URLDecoder.decode(URLDecoder.decode(options,"utf-8"),"utf-8");
		String[] result = options.split(",");
		attributeListService.saveOptionsBatch(type, result);
		jsonOut("添加成功");
		return null;
	}
	
	public String adl() throws IOException {
		String agent = request.getHeader("User-Agent");
		String id = request.getParameter("id");
		if(id == null)
			return null;
		int appId = Integer.parseInt(id);
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		AppUpdateTab appAndroid = appUpdateService.getMaxVersion(
				appId, new String[]{"varAppDownloadUrl"}, GenericConstants.OPERATION_SYS_ANDROID);
		AppUpdateTab appIos = appUpdateService.getMaxVersion(
				appId, new String[]{"varAppDownloadUrl","varIosInstallUrl"}, GenericConstants.OPERATION_SYS_IOS);
		if(agent.contains("Android")) {
			String result = null;
			if(appAndroid==null){
				result="没找到此应用的Android版";
			} else {
				result="<script type='text/javascript'>" +
					"window.location='"+appAndroid.getVarAppDownloadUrl()+"'" +
					"</script>";
				log.info("Android用户通过分享下载应用" + appId);
			}
			out.print(result);
		} else if (agent.contains("iPhone") || agent.contains("iPad")) {
			String result = null;
			if (appIos == null) {
				result="没找到此应用的IOS版";
			} else {
				result="<script type='text/javascript'>" +
					"window.location='"+appIos.getVarIosInstallUrl()+"'" +
					"</script>";
				log.info("IOS用户通过分享下载应用" + appId);
			}
			out.print(result);
		} else {
			out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
			out.println("<HTML>");
			out.println("  <HEAD><TITLE>应用下载</TITLE></HEAD>");
			out.println("  <BODY>");
			if(appAndroid==null){
				out.println("没找到此应用的Android版本<br><br>");
			} else {
				out.println(" <a href='"+appAndroid.getVarAppDownloadUrl()+"'>Android下载</a><br><br>");
			}
			if (appIos == null) {
				out.println("没找到此应用的IOS版本<br>");
			}else {
				String[] urls = StringUtils.split(appIos.getVarAppDownloadUrl(),",");
				String gotoappUrl = urls[0].contains("_gotoapp.ipa")?urls[0]:urls[1];
				out.println(" <a href='"+gotoappUrl+"'>IOS下载</a>");
			}
			out.println("  </BODY>");
			out.println("</HTML>");
		}
		out.flush();
		out.close();
		return null;
	}
	
	private String getIconUrl(int type) {
		if (type == 8) {
			return "WORKDIR/SYS_MATERIAL/ICON";
		}
		if (type == 7) {
			return "WORKDIR/SYS_MATERIAL/TITLE_BAR";
		}
		if (type == 3) {
			return "WORKDIR/SYS_MATERIAL/APP_BK";
		}
		if (type == 6) {
			return "WORKDIR/SYS_MATERIAL/NAV_BAR";
		}
		return null;
	}
}
